import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2024-11-24
 * Time: 19:59
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
        // 找倒数第一个非叶子节点，从该节点位置开始往前一直到根节点，遇到一个节点，应用向下调整
        for (int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            siftDown(elem, parent);
        }
    }

    /**
     * 向下调整
     * @param elem
     * @param parent
     */
    public void siftDown(int[] elem, int parent) {
        int size = usedSize;
        int child = 2 * parent + 1;
        while (child < size) {
            if (child + 1 < size  && elem[child] < elem[child + 1]) {
                child = child + 1;
            }
            int tmp = elem[parent];
            elem[parent] = elem[child];
            elem[child] = tmp;
            parent = child;
            child = 2 * parent + 1;
        }
    }

    public void push(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize] = val;
        usedSize++;
        siftUp(usedSize-1);
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    public void siftUp(int child) {
        int parent = (child - 1) / 2;
        while (child > 0) {
            if (elem[parent] < elem[child]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }

    public void poll() {
        if (isEmpty()) {
            throw new HeapEmptyException("优先级队列是空的!");
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        siftDown(elem, 0);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public int peek() {
        if (isEmpty()) {
            throw new HeapEmptyException("优先级队列是空的!");
        }
        return elem[0];
    }
}
